package cn.spream.jstudy.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Created by sjx on 2015/11/6.
 */
public class NettyClient {

    private final Bootstrap bootstrap = new Bootstrap();
    private String host;
    private int port;
    private ChannelHandler channelHandler;
    private ChannelFuture channelFuture;
    private EventLoopGroup workerEventLoopGroup;

    public NettyClient(String host, int port, ChannelHandler channelHandler) {
        this.host = host;
        this.port = port;
        this.channelHandler = channelHandler;
    }

    public void start() throws InterruptedException {
        workerEventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(workerEventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new ChannelHandler[]{new NettyEncoder(), new NettyDecoder(), channelHandler});
            }
        });
        channelFuture = bootstrap.connect(host, port).sync();
    }

    public ChannelFuture send(Message message) {
        return channelFuture.channel().writeAndFlush(message);
    }

    public void stop() {
        if (workerEventLoopGroup != null) {
            workerEventLoopGroup.shutdownGracefully();
        }
    }

}
